<template>
  <main-card-admin title="课程管理" :main-body-style-obj="{ paddingTop: '32px' }">
    <template #tool-btn>
      <a-button v-if="checkKey('admin-class-manage-add')" type="primary" @click="handleEdit">新建</a-button>
    </template>
    <template #screen-space>
      <div class="search-box">
        <div class="search-box-left">
          <a-select
            v-model:value="selectClassify"
            class="w-140"
            :field-names="{ label: 'v', value: 'id' }"
            :options="classifyOptions"
            @change="classifyChange"
          />
          <a-select
            v-model:value="selectRank"
            class="w-140"
            :field-names="{ label: 'v', value: 'id' }"
            :options="rankOptions"
            @change="classifyChange"
          />
          <a-select
            v-model:value="selectStatus"
            class="w-140"
            :field-names="{ label: 'v', value: 'id' }"
            :options="statusOptions"
            @change="classifyChange"
          />
        </div>
        <div>
          <a-input v-model:value="courseName" v-trim allow-clear placeholder="请输入名称" class="w-328" @press-enter="classifyChange">
            <template #prefix><SearchOutlined /></template>
          </a-input>
        </div>
      </div>
    </template>
    <div>
      <a-table
        :style="{ width: '100%' }"
        :data-source="taskTableSource"
        :columns="taskTableColumns"
        :pagination="false"
        :custom-row="r => ({ onClick: () => handleToDetail(r) })"
        :loading="loading"
        class="header-right-angle admin-table"
        @change="tableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'createTime'">
            <div class="describe-class">
              {{ dateFormat(record.createTime) }}
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'updateTime'">
            <div class="describe-class">
              {{ dateFormat(record.updateTime) }}
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'status'">
            {{ obj[record.status] }}
          </template>
          <template v-else-if="column.dataIndex === 'tools'">
            <a-button type="link" style="margin-right: 12px" :disabled="record.status !== 1" @click="classInfo(record)">详情</a-button>
            <a-dropdown v-if="checkKey('admin-class-manage-edit') | checkKey('admin-class-manage-del')" placement="bottomRight" @click.stop>
              <a-button type="text" class="icon-only-btn" @click.stop>
                <i class="iconfont icon-more-line"></i>
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item
                    v-if="checkKey('admin-class-manage-edit')"
                    :disabled="record.status !== 1"
                    class="menu-icon-item"
                    @click="handleTableEdit(record)"
                  >
                    编辑
                  </a-menu-item>
                  <a-menu-item
                    v-if="checkKey('admin-class-manage-del')"
                    :disabled="record.status === 0"
                    class="menu-icon-item"
                    @click="handleDelete(record)"
                  >
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
          <template v-else-if="column.dataIndex === 'categories'">
            <label-classification :label-list="record.categories" />
          </template>

          <template v-else-if="column.dataIndex === 'levels'">
            <label-classification :label-list="record.levels" :label-options-style="{ color: '#D61860', background: '#d6186014' }" />
          </template>
          <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
        </template>
      </a-table>
      <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getDataList" />
    </div>
  </main-card-admin>
  <delete-confirm-dialog
    v-model:show="dialogShow"
    label="请输入课程名称"
    :confirm-name="deleteFileName"
    :msg="`已有${collectNumber}人收藏此课程，请确认是否删除？`"
    @ok="okDelete"
  />
</template>

<script lang="ts" setup>
  import { message, TableProps } from 'ant-design-vue'
  import { dateFormat } from 'g6-fn'
  import { ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRouter } from 'vue-router'

  import MainCardAdmin from '@/components/MainCardAdmin/index.vue'
  import { checkKey } from '@/directives/auth'
  import useList from '@/hooks/use-list'
  import { adminCollectionApi, courseAdminApi, tagManageApi } from '@/services/api'
  import { filterTableColumns, replaceEmptyStr } from '@/utils'

  import { ClassListType, DictionaryVOResponse, TableReq } from '../types/index'
  interface TaskStatus {
    id: string
    v: string
  }
  let router = useRouter()
  let obj = ref<string[]>(['保存中', '保存成功', '保存失败'])
  // ResponseData<ClassLabelType[]
  const { runAsync: getDataLabel } = useRequest<ResponseData<DictionaryVOResponse[]>>(tagManageApi.list, {
    onSuccess: res => {
      for (let item of res.data) {
        if (item.type === 'course_level') {
          rankOptions.value.push(item)
        } else {
          classifyOptions.value.push(item)
        }
      }
    }
  })

  const courseName = ref<string>('')
  /********************分类************************/

  const selectClassify = ref<number>(9999)
  let classifyOptions = ref<(TaskStatus | DictionaryVOResponse)[]>([
    {
      v: '全部分类',
      id: 9999
    }
  ])
  getDataLabel({ type: 'course_level' })

  /********************分级************************/

  const selectRank = ref<number>(9999)
  let rankOptions = ref<(TaskStatus | DictionaryVOResponse)[]>([
    {
      v: '全部级别',
      id: 9999
    }
  ])
  getDataLabel({ type: 'course_category' })

  /********************表格************************/
  // 课程收藏数
  const collectNumber = ref(0)

  const {
    pageForm,
    dataList: taskTableSource,
    loading,
    getDataList
  } = useList<TableReq, ClassListType[]>(courseAdminApi.list, {
    order: 'desc'
  })

  // 状态
  const selectStatus = ref<number>(999)
  const statusOptions = [
    {
      v: '全部状态',
      id: 999
    },
    {
      v: '保存成功',
      id: 1
    },
    {
      v: '保存中',
      id: 0
    },
    {
      v: '保存失败',
      id: 2
    }
  ]
  // 表格列
  const taskTableColumns = ref(
    filterTableColumns([
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        width: 160
      },
      {
        title: '分类',
        dataIndex: 'categories',
        key: 'categories',
        width: 280
      },
      {
        title: '级别',
        dataIndex: 'levels',
        key: 'levels',
        width: 280
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 100
      },
      {
        title: '描述',
        dataIndex: 'description',
        key: 'description'
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 180,
        isSort: true
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        width: 180,
        isSort: true
      },
      {
        title: '',
        width: 98,
        dataIndex: 'tools'
      }
    ])
  )

  // 表格全选
  const handleToDetail = (r: ClassListType[]) => {
    console.log(r)
    console.log(courseName)
  }

  const handleTableEdit = (row: ClassListType | any) => {
    // 将数据传递
    router.push({
      path: '/admin/class-manage/list/edit',
      query: {
        type: 'edit',
        id: row.id
      }
    })
  }

  // 删除表格数据操作
  const dialogShow = ref<boolean>(false)
  const deleteFileName = ref<string>('')
  let deleteId = ''

  const handleDelete = async (row: ClassListType | any) => {
    deleteId = ''
    dialogShow.value = true
    deleteFileName.value = row.name
    deleteId = row.id
    let { data: num } = await adminCollectionApi.numberOfCollections({ favoriteType: 1, objectId: row.id })
    collectNumber.value = num
  }

  const okDelete = async () => {
    await courseAdminApi.del({}, { isAddUid: true, urlParams: { id: deleteId } })
    message.success('删除成功')
    dialogShow.value = false
    getDataList()
  }

  // 详情跳转
  const classInfo = (row: ClassListType | any) => {
    window.open(`/class-square/class-particulars/${row.id}`, '_blank')
  }

  // 表格变化
  const tableChange: TableProps<ClassListType>['onChange'] = (pagination, filters, sorter: any) => {
    pageForm.value.order = sorter.order === 'ascend' ? 'asc' : 'desc'
    pageForm.value.columns = sorter.field
    if (!sorter.order) {
      pageForm.value.columns = 'createTime'
      pageForm.value.order = 'desc'
    }
    getDataList({ offset: 1 })
  }

  /********************分页************************/

  /********************新建************************/
  const handleEdit = () => {
    router.push({
      path: '/admin/class-manage/list/edit',
      query: {
        type: 'add'
      }
    })
  }

  // 类别改变
  const classifyChange = () => {
    let setCategoryId = selectClassify.value === 9999 ? null : selectClassify.value
    let setLevelId = selectRank.value === 9999 ? null : selectRank.value
    let setStatusId = selectStatus.value === 999 ? null : selectStatus.value
    getDataList({ categoryId: setCategoryId, levelId: setLevelId, name: courseName.value, offset: 1, status: setStatusId })
  }

  getDataList()
</script>
<style lang="less" scoped>
  .span-list {
    display: flex;
    gap: 8px;
  }

  .describe-class {
    display: -webkit-box;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal;

    /* autoprefixer: ignore next */
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
  }

  .search-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;

    .search-box-left {
      display: flex;
      gap: 8px;
      align-items: center;
    }
  }
</style>
